package com.dexilaonian.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.dexilaonian.MainActivity;
import com.dexilaonian.R;
import com.dexilaonian.adpter.OrderDetailAdapter;
import com.dexilaonian.alipay.PayResult;
import com.dexilaonian.bean.OrderDetailBean;
import com.dexilaonian.bean.WeiXinBean;
import com.dexilaonian.ui.BaseActivity;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.JsonUtil;
import com.dexilaonian.utils.Okhttp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bakerj.backgrounddarkpopupwindow.BackgroundDarkPopupWindow;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class PayingActivity extends BaseActivity {

    private static final int LDADDATA = 3;
    private static final int SDK_PAY_FLAG = 4;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.base_title_service3)
    TextView baseTitleService3;
    @Bind(R.id.pay_name)
    TextView payName;
    @Bind(R.id.pay_phone)
    TextView payPhone;
    @Bind(R.id.pay_address)
    TextView payAddress;
    @Bind(R.id.rl_pay_dingzhi)
    RelativeLayout rlPayDingzhi;
    @Bind(R.id.pay_listview)
    ListView payListview;
    @Bind(R.id.pay_num)
    TextView payNum;
    @Bind(R.id.pay_time)
    TextView payTime;
    @Bind(R.id.pay_all_price)
    TextView payAllPrice;
    @Bind(R.id.pay_freight)
    TextView payFreight;
    @Bind(R.id.pay_discounts)
    TextView payDiscounts;
    @Bind(R.id.all_pay_money)
    TextView allPayMoney;
    @Bind(R.id.btn_cancle_pay)
    Button btnCanclePay;
    @Bind(R.id.btn_tijiao_pay)
    Button btnTijiaoPay;

    private int positon;
    private TextView totalMoney;
    private BackgroundDarkPopupWindow window;
    private String orderId = "";
    private List<OrderDetailBean> producelist = new ArrayList<>();
    private String response1;
    private WeiXinBean weiXinBean;
    private IWXAPI api;
    private String totalPrice;

    @Override
    public int getLayoutID() {
        return R.layout.activity_paying;
    }

    @Override
    public void initView() {
        api = WXAPIFactory.createWXAPI(this, "wx4263464eb114ed63");
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        baseTitleService3.setText("等待付款");
        Intent intent = getIntent();
        if (intent != null) {
            Bundle extras = intent.getExtras();
            if (extras != null) {
                orderId = extras.getString("OrderId");
            }
        }
        initPayStatus();
    }

    private void initPayStatus() {
        showProgressBar(true);
        String pay_status_url = Constant.base_url + "/sale_order/order_detail.do";
        Map<String, String> pay_status_map = new HashMap<>();
        pay_status_map.put("OrderId", orderId);
        Okhttp.postString(true, pay_status_url, pay_status_map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showProgressBar(false);
                showToast(state);
            }

            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                Log.e("TTTTTpaystatus", response);
                try {
                    JSONObject js = new JSONObject(response);
                    String data = js.optString("data");
                    JSONObject json = new JSONObject(data);
                    String refNo = json.optString("refNo");
                    String transportPrice = json.optString("transportPrice");
                    String create_time = json.optString("create_time");
                    totalPrice = json.optString("totalPrice");
                    String discountPrice = json.optString("discountPrice");
                    String orderPrice = json.optString("orderPrice");
                    String order_id = json.optString("order_id");
                    String status = json.optString("status");
                    String receiverAddress = json.optString("receiverAddress");
                    String receiverPhone = json.optString("receiverPhone");
                    String receiverName = json.optString("receiverName");
                    if (!TextUtils.isEmpty(refNo)) {
                        payNum.setText("订单号:"+refNo);
                    }
                    if (!TextUtils.isEmpty(transportPrice)) {
                        payFreight.setText("￥"+transportPrice);
                    }
                    if (!TextUtils.isEmpty(create_time)) {
                        payTime.setText("创建于:"+create_time);
                    }
                    if (!TextUtils.isEmpty(totalPrice)) {
                        payAllPrice.setText("￥"+ totalPrice);
                    }
                    if (!TextUtils.isEmpty(discountPrice)) {
                        payDiscounts.setText("￥"+discountPrice);
                    }
                    if (!TextUtils.isEmpty(orderPrice)) {
                        allPayMoney.setText("￥"+orderPrice);
                    }
                    if (!TextUtils.isEmpty(receiverName)) {
                        payName.setText("收货人:"+receiverName);
                    }
                    if (!TextUtils.isEmpty(receiverAddress)) {
                        payAddress.setText("收货地址:"+receiverAddress);
                    }
                    if (!TextUtils.isEmpty(receiverPhone)) {
                        payPhone.setText(receiverPhone);
                    }
                    String productDetail = json.optString("productDetail");
                    ArrayList<OrderDetailBean> orderBeen = JsonUtil.json2beans(productDetail, OrderDetailBean.class);
                    producelist.clear();
                    producelist.addAll(orderBeen);
                    OrderDetailAdapter orderDetailAdapter = new OrderDetailAdapter(PayingActivity.this, producelist);
                    payListview.setAdapter(orderDetailAdapter);
                    orderDetailAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
                showToast(state);
            }
        });
    }

    @OnClick({R.id.back, R.id.btn_cancle_pay, R.id.btn_tijiao_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.btn_cancle_pay:
                initCancle();
                break;
            case R.id.btn_tijiao_pay:
                showPopwindow_pay();
                break;
        }
    }

    private void initCancle() {
        showProgressBar(true);
        String item_cancle_url = Constant.base_url + "/sale_order/cancel.do";
        Map<String, String> item_cancle_map = new HashMap<String, String>();
        item_cancle_map.put("OrderId", orderId);
        Okhttp.postString(true, item_cancle_url, item_cancle_map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showToast(state);
                showProgressBar(false);
            }

            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 0) {
                        Toast.makeText(PayingActivity.this,"取消成功",Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(PayingActivity.this,MainActivity.class);
                        intent.putExtra("user", 2);
                        startActivity(intent);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showToast(state);
                showProgressBar(false);
            }
        });
    }

    /**
     * 显示popupWindow
     */
    private void showPopwindow_pay() {
        // 利用layoutInflater获得View
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.popwindow_new_pay, null);
        RelativeLayout alipay = (RelativeLayout) view.findViewById(R.id.rl_new_alipay);
        RelativeLayout wechat = (RelativeLayout) view.findViewById(R.id.rl_new_wechat);
        final ImageView ivAlipay = (ImageView) view.findViewById(R.id.iv_new_alipay2);
        final ImageView ivWechat = (ImageView) view.findViewById(R.id.iv_new_wechat3);
        final TextView payMoney = (TextView) view.findViewById(R.id.tv_new_pay);
        TextView totalMoney = (TextView) view.findViewById(R.id.new_total_money);
        //  balance_pay.setText("（余额：￥" + total_deposit + "）");
        // 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()
        totalMoney.setText("￥" + totalPrice);
        window = new BackgroundDarkPopupWindow(view,
                WindowManager.LayoutParams.MATCH_PARENT,
                1100);
        window.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        window.setFocusable(true);
        window.setDarkStyle(-1);
        window.resetDarkPosition();
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        window.setBackgroundDrawable(dw);
        window.setBackgroundDrawable(getResources().getDrawable(R.color.colorpopuwindow));
        // 设置popWindow的显示和消失动画
        window.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 在底部显示
        window.showAtLocation(PayingActivity.this.findViewById(R.id.rllll),
                Gravity.BOTTOM, 0, 0);
   /*     deshengka.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivka.setVisibility(View.VISIBLE);
                ivAlipay.setVisibility(View.GONE);
                ivWechat.setVisibility(View.GONE);
                positon = 0;
            }
        });*/
        alipay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivAlipay.setVisibility(View.VISIBLE);
                ivWechat.setVisibility(View.GONE);
                positon = 1;
            }
        });
        wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivWechat.setVisibility(View.VISIBLE);
                ivAlipay.setVisibility(View.GONE);
                positon = 2;
            }
        });
        payMoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (positon == 1) {
                    if (!TextUtils.isEmpty(orderId)) {
                        aliPay(orderId);
                    } else {
                        showToast("orderId为空");
                    }
                    positon = 1;
                } else {
                    Log.e("TTTorderId", orderId);
                    if (!TextUtils.isEmpty(orderId)) {
                        wechatPay(orderId);
                    } else {
                        showToast("orderId为空");
                    }
                }
                window.dismiss();
            }
        });
        //popWindow消失监听方法
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
    }

    private void wechatPay(String orderId3) {
        showProgressBar(true);
        String wechat_url = Constant.base_url + "/pay_method/save.do";
        Map<String, String> wechat_map = new HashMap<>();
        wechat_map.put("orderId", orderId3);
        wechat_map.put("payMethodType", 2 + "");
        Okhttp.postString(true, wechat_url, wechat_map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showProgressBar(false);
                showToast(state);
            }

            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                Log.e("TTTT获取微信支付参数", response);
                try {
                    response1 = response.replaceAll("package", "packageValue");
                    JSONObject object = new JSONObject(response1);
                    int status = Integer.parseInt(object.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(PayingActivity.this, LoginActivity.class));
                        return;
                    }
                    if (status == 18) {
                        showToast("系统错误");
                        return;
                    }
                    if (status == 0) {
                        String data = object.optString("data");
                        JSONObject jsonObject = new JSONObject(data);
                        String orderStr = jsonObject.optString("orderStr");

                        Log.e("TTTTTTTTTTTWEIXIN", response1 +"==="+response+"=="+orderStr);
                        weiXinBean = JSON.parseObject(orderStr, WeiXinBean.class);
                        Log.e("TTTresult", weiXinBean.getAppid() + "==" + weiXinBean.getTimestamp() + "==" + weiXinBean.getPartnerid());
                        PayReq req = new PayReq();
                        req.appId = weiXinBean.getAppid();
                        req.partnerId = weiXinBean.getPartnerid();
                        req.prepayId = weiXinBean.getPrepayid();
                        req.nonceStr = weiXinBean.getNoncestr();
                        req.timeStamp = weiXinBean.getTimestamp();
                        req.sign = weiXinBean.getSign();
                        req.packageValue= weiXinBean.getPackageValue();
                        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                        //3.调用微信支付sdk支付方法
                        api.sendReq(req);
                        //  sendPayRequest();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
                showToast(state);
            }
        });
    }
    /**调用微信支付**/
    public void sendPayRequest() {
        showToast("开发中.....");
    }
    private void aliPay(String orderId2) {
        showProgressBar(true);
        String pay_url = Constant.base_url + "/pay_method/save.do";
        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId2);
        map.put("payMethodType", 1 + "");
        Okhttp.postString(true, pay_url, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showProgressBar(false);
                showToast(state);
            }

            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                Log.e("TTTT获取支付参数", response);
                try {
                    JSONObject object = new JSONObject(response);
                    int status = Integer.parseInt(object.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(PayingActivity.this, LoginActivity.class));
                        return;
                    }
                    if (status == 18) {
                        showToast("系统错误");
                        return;
                    }
                    if (status == 0) {
                        showToast("获取支付参数成功");
                        JSONObject pay_data = new JSONObject(response);
                        String data = pay_data.optString("data");
                        JSONObject order_json = new JSONObject(data);
                        final String orderInfo = order_json.optString("orderStr");// 订单信息

                        Runnable payRunnable = new Runnable() {
                            @Override
                            public void run() {
                                PayTask alipay = new PayTask(PayingActivity.this);
                                Map<String, String> result = alipay.payV2(orderInfo, true);
                               /* PayTask alipay = new PayTask(ConfirmStoreActivity.this);
                                String result = String.valueOf(alipay.payV2(orderInfo, true));*/
                                Message msg = new Message();
                                msg.what = SDK_PAY_FLAG;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
                            }
                        };
                        // 必须异步调用
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
                showToast(state);
            }
        });

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    //  PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                            /**
                             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                             */
             /*       String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();*/
                            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Log.e("TTTTresultStatus", resultStatus);
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (resultStatus.equals("9000")) {
                        Toast.makeText(PayingActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(PayingActivity.this, SuccessPayActivity.class);
                        startActivity(intent);
                    } else if (resultStatus.equals("4000")) {
                        // 4000为支付失败，包括用户主动取消支付，或者系统返回的错误
                        Toast.makeText(PayingActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    } else if (resultStatus.equals("6001")) {

                        // 6001为取消支付，或者系统返回的错误
                        Toast.makeText(PayingActivity.this, "取消支付", Toast.LENGTH_SHORT).show();

                    } else if (resultStatus.equals("8000")) {
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        Toast.makeText(PayingActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                    } else {
                        // 其他为系统返回的错误
                        Toast.makeText(PayingActivity.this, "支付错误", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

            }
        }
    };
}
